<?php

/**
 * 后台登录退出控制器
 */

namespace app\admin\controller;

use Exception;
use think\Request;
use app\admin\model\AdminUser;
use app\admin\validate\AdminUserValidate;
use think\captcha\facade\Captcha;
use think\exception\ValidateException;
use think\facade\Event;
use tools\GeeTest;

class AuthController extends Controller
{

    public $authExcept = [
        'login',
        'captcha',
        'initGeeTest',
        'refreshToken',
        'logout'
    ];

    //登录
    public function login(Request $request, AdminUser $model, AdminUserValidate $validate)
    {

        if ($request->isPost()) {
            try {
                $login_config = setting('admin.login');

                $param = $request->param();

                switch ($login_config['captcha']) {
                    case 1:
                        if (!captcha_check($param['captcha'])) {
                            return error('验证码错误');
                        }
                        break;
                    case 2:
                        $config  = setting('admin.login');
                        $geeTest = new GeeTest($config['geetest_id'], $config['geetest_key']);
                        $data = array(
                            'user_id'     => session('gt_uid'),
                            'client_type' => 'web',
                            'ip_address'  => $request->ip(),
                        );
                        if (session('gt_server') == 1) {
                            $gee_test_result = $geeTest->successValidate($param['geetest_challenge'], $param['geetest_validate'], $param['geetest_seccode'], $data);
                            if (!$gee_test_result) {
                                return error('验证失败');
                            }
                        } else {
                            if (!$geeTest->failValidate($param['geetest_challenge'], $param['geetest_validate'])) {
                                return error('验证失败');
                            }
                        }
                        break;
                }

                $validate_result = $validate->scene('login')->check($param);
                if (!$validate_result) {
                    return error($validate->getError());
                }
                //如果需要验证登录token
                if ($login_config['token']) {
                    $check = $request->checkToken('__token__', $param);
                    if (!$check) {
                        throw new ValidateException('无效token');
                    }
                }

                $user = $model::login($param);
            } catch (ValidateException $e) {
                $msg = $e->getMessage();
                return error($msg);
            } catch (Exception $e) {
                // 记录错误次数
                $this->setLoginLimit();
                return error($e->getMessage());
            }

            $this->setLoginDeviceId($user);
            self::authLogin($user, true);

            $redirect = session('redirect') ?? url('admin/index/index');

            return success('登录成功', $redirect);
        }

        $this->setAdminInfo();
        $this->admin['title'] = '登录';
        $this->assign([
            //登录设置，参考/config/admin/admin.php文件配置
            'login_config' => setting('admin.login'),
            'admin'         => $this->admin,

        ]);

        return $this->fetch();
    }

    //退出
    public function logout()
    {
        Event::trigger('AdminUserLogout', $this->user);
        self::authLogout();
        return redirect(url('login'));
    }


    //极验初始化
    public function initGeeTest(Request $request)
    {

        $config  = setting('admin.login');
        $geeTest = new GeeTest($config['geetest_id'], $config['geetest_key']);

        $ip = $request->ip();
        $ug = $request->header('user-agent');

        $data = array(

            'gt_uid'      => md5($ip . $ug),
            'client_type' => 'web',
            'ip_address'  => $ip,
        );

        $status = $geeTest->preProcess($data);

        session('gt_server', $status);
        session('gt_uid', $data['gt_uid']);

        return success($status, URL_CURRENT, $geeTest->getResponse());
    }
    //ThinkPHP 图形验证码
    public function captcha()
    {

        return  Captcha::create();
    }
    //刷新表单token
    public function refreshToken(Request $request)
    {

        return success('获取成功', URL_CURRENT, ['token' => token()]);
    }
}
